<?php
declare (strict_types = 1);

namespace app\common\model\User;

use app\common\model\Region;

use app\common\model\Config;

use think\Model;

/**
 * @mixin \think\Model
 */
class User extends Model
{
    //指定数据表
    protected $table = 'pre_user';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    // 定义创建时间
    protected $createTime = 'createtime';

    // 定义更新时间
    protected $updateTime = false;

    // 定义追加字段列表 => 前后端分离项目
    protected $append = [
        // 地区字段
        'region_text',
        'avatar_cdn',
        'sex_text',
        'cover_cdn',
        'region'
    ];

    public function getRegionAttr($value,$data)
    {
        $province = Region::where(['code' => $data['province']])->find();
        $city = Region::where(['code' => $data['city']])->find();
        $district = Region::where(['code' => $data['district']])->find();

        $data = [
            $province['name'],
            $city['name'],
            $district['name'],
        ];

        return $data;
    }

    public function getSexTextAttr($value,$data) {
        $SexList = [0 => '保密',1 => '男',2 => '女'];

        return $SexList[$data['sex']];
    }

    public function getCoverCdnAttr($value,$data) {

        // $cover = is_file($data['cover']) ? $data['cover'] : '/static/home/res/images/cover.jfif';

        // $cdn = Config::where(['key' => 'cdn'])->value('value');

        // return $cdn.'/'.$cover;

        $cover = $data['cover'];

        if($cover) {
            $cdn = Config::where(['key' => 'cdn'])->value('value');

            return $cdn.'/'.$cover;

        }

        return '';
    }

    public function getAvatarCdnAttr($value,$data) {

        $avatar = is_file($data['avatar']) ? $data['avatar'] : '/static/home/res/images/avatar/default.png';

        $cdn = Config::where(['key' => 'cdn'])->value('value');

        return $cdn.'/'.$avatar;
    }

    // 定义不存在字段 region_text => RegionText
    public function getRegionTextAttr($value,$data)
    {
        $province = Region::where(['code' => $data['province']])->value('name');
        $city = Region::where(['code' => $data['city']])->value('name');
        $district = Region::where(['code' => $data['district']])->value('name');

        $region_text = '';

        if($province)
        {
            $region_text .= $province . '-';
        }

        if($city)
        {
            $region_text .= $city . '-';
        }

        if($district)
        {
            $region_text .= $district;
        }

        return $region_text;
    }
}
